package dex.micros_gdc

import java.text.DateFormat
import java.text.SimpleDateFormat

import org.springframework.dao.DataIntegrityViolationException

import dex.micros_gdc.common.SQLConstants

class OvertimeController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	static DateFormat DF = new SimpleDateFormat("MM/dd/yyyy")
	// Export service provided by Export plugin
	def exportService
	def grailsApplication  //inject GrailsApplication

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)

		def overtimes = Overtime.list(params)
		export(overtimes)
        [overtimeInstanceList: overtimes, overtimeInstanceTotal: overtimes.size()]
    }

    def create() {
		params.otDate = new Date()
        [overtimeInstance: new Overtime(params), dueDateTemp: DF.format(new Date()), teamResources: getActiveResources()]
    }

    def save() {
		params.otDate = DF.parse(params.otDateTemp)

        def overtimeInstance = new Overtime(params)
        if (!overtimeInstance.save(flush: true)) {
            render(view: "create", model: [overtimeInstance: overtimeInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'overtime.label', default: 'Overtime'), overtimeInstance.id])
        redirect(action: "show", id: overtimeInstance.id)
    }

    def show(Long id) {
        def overtimeInstance = Overtime.get(id)
        if (!overtimeInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'overtime.label', default: 'Overtime'), id])
            redirect(action: "list")
            return
        }

        [overtimeInstance: overtimeInstance]
    }

    def edit(Long id) {
        def overtimeInstance = Overtime.get(id)
        if (!overtimeInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'overtime.label', default: 'Overtime'), id])
            redirect(action: "list")
            return
        }

        [overtimeInstance: overtimeInstance, otDateTemp: DF.format(overtimeInstance.otDate), teamResources: getActiveResources()]
    }

    def update(Long id, Long version) {
		params.otDate = DF.parse(params.otDateTemp)
        def overtimeInstance = Overtime.get(id)
        if (!overtimeInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'overtime.label', default: 'Overtime'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (overtimeInstance.version > version) {
                overtimeInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'overtime.label', default: 'Overtime')] as Object[],
                          "Another user has updated this Overtime while you were editing")
                render(view: "edit", model: [overtimeInstance: overtimeInstance])
                return
            }
        }

        overtimeInstance.properties = params

        if (!overtimeInstance.save(flush: true)) {
            render(view: "edit", model: [overtimeInstance: overtimeInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'overtime.label', default: 'Overtime'), overtimeInstance.id])
        redirect(action: "show", id: overtimeInstance.id)
    }

    def delete(Long id) {
        def overtimeInstance = Overtime.get(id)
        if (!overtimeInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'overtime.label', default: 'Overtime'), id])
            redirect(action: "list")
            return
        }

        try {
            overtimeInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'overtime.label', default: 'Overtime'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'overtime.label', default: 'Overtime'), id])
            redirect(action: "show", id: id)
        }
    }


	private def getActiveResources() {
		return Resource.executeQuery(SQLConstants.ALL_ACTIVE_RESOURCES_QUERY)
	}

	private def export(overtimes){
		if(params?.format && params.format != "html"){
			response.contentType = grailsApplication.config.grails.mime.types[params.format]
			response.setHeader("Content-disposition", "attachment; filename=OT.${params.extension}")

			List fields = [
				"teamMember",
				"otDate",
				"otHour",
				"comments",
				"closedFlag"
			]

			Map labels = [
				"teamMember":"Team Member",
				"otDate":"OT Date",
				"otHour": "OT Hour",
				"comments":"Comments",
				"closedFlag":"Closed Flag"]

			Map parameters = ["column.widths": [
					0.20,
					0.15,
					0.12,
					0.40,
					0.15
				]]
			exportService.export(params.format, response.outputStream, overtimes, fields,labels,[:], parameters)
		}
	}
}
